<?php

require_once('config.php');
require_once('functions/general.php');
require_once('functions/sql.php');
require_once('sql/sql_discussion.php');
require_once('alien/Smarty/Smarty.class.php');
require_once('pages/discussion.php');

define('ACTION_NEW_THREAD', "new");
define('ACTION_THREAD_REPLY', "thread_reply");

define('VIEW_SUBBACK', "subback");
define('VIEW_THREAD_FORM', "thread_form");
define('VIEW_THREAD', "thread");

session_start();
$smarty = new Smarty;
$smarty->assign('CONFIG', $CONFIG);
$smarty->template_dir 
    = array('templates', 'templates/discussion', 'templates/common');
$logged_in = logged_in_status($smarty);
$mysql_link = get_mysql_link();

$discussion = new Discussion($smarty, $mysql_link);

$tpl = null;

# Actions
if (isset($_POST['action'])) {
    $action = $_POST['action'];
    switch ($action) {
        case ACTION_NEW_THREAD:
            //Create a new thread
            list($text, $title, $sage)
                = array_extract_vars($_POST, array('text', 'title', 'sage'));
            $tpl = $discussion->add_new_thread(
                    $text, $title, $sage, $logged_in);
            break;

        case ACTION_THREAD_REPLY:
            list($id, $text, $sage)
                = array_extract_vars($_POST, array('reply', 'text', 'sage'));
            $tpl = $discussion->add_new_reply($id, $text, $sage, $logged_in);
            break;

        default:
            print("Unknown action" . htmlentities($_POST['action']));
            assert(false);
    }
}

if (isset($_GET['view'])) {
    $view = $_GET['view'];
    switch ($view) {
        case VIEW_THREAD:
            $thread_id = $_GET['t'];
            $tpl = $discussion->show_thread($thread_id);
            break;
        case VIEW_THREAD_FORM:
            $tpl = $discussion->show_thread_form();	
            break;
        case VIEW_SUBBACK:
            $tpl = $discussion->show_subback();
            break;
        default:
            print "Unknown view: " . htmlentities($view);
            break;
    }
}

if (is_null($tpl))
    $tpl = $discussion->show_overview();

mysql_close($mysql_link);
$smarty->display($tpl);

?>
